/**
 * @计算某年某月到某年某月之间的天数
 *
 * @author	 wangshikun <wangshikun2010@gmail.com>
 * @copyright	(c) 2012 wangshikun <wangshikun2010@gmail.com>
 * @license	http://www.opensource.org/licenses/mit-license.php The MIT License
 * @package	default
 * @subpackage	default
 */

#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>

typedef struct date {
	int year;
	int month;
	int day;
} date;

int f(struct date d);
int g(struct date d);
int getDays(struct date d);
struct date getDate(char* prompt);

int main(int argc, char *argv[]) {
	printf("欢迎使用日期计算器，您说输入的日期必须晚于1900年3月1日！\n\n");

	do {
		struct date date1 = getDate("请输入开始日期");
		struct date date2 = getDate("请输入结束日期");

		int days = getDays(date2) - getDays(date1);

		printf("\t\t\t  间隔%d天\n\n", days);
	} while (true);

	return 0;
}

int f(struct date d) {
	if (d.month <= 2) {
		return --d.year;
	} else {
		return d.year;
	}
}

int g(struct date d) {
	if (d.month <= 2) {
		return (d.month + 13);
	} else {
		return (d.month + 1);
	}
}

int getDays(struct date d) {
	return (1461 * f(d)) / 4 + (153 * g(d)) / 5 + d.day;
}

struct date getDate(char* prompt) {
	struct date d;
	int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

	do {
		printf("%s(年-月-日): ", prompt);
		scanf("%d-%d-%d", &d.year, &d.month, &d.day);

		// is leap year?
		if (d.year%400 == 0 || (d.year%4 == 0 && d.year%100 != 0)) {
			days[1] = 29;
		}

		// check year, mont, day
		if ((d.year >= 1900)					// yeay is valid
			&& (d.month > 0 && d.month < 13)	// month is valid
			&& (d.day > 0 && d.day <= days[d.month-1])
		) {
			break;
		}
	} while (true);

	return d;
}
